package com.robot.merchant.service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.robot.merchant.constant.Constant;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import util.IdWorker;

import com.robot.merchant.dao.CompanyDao;
import com.robot.merchant.pojo.Company;

/**
 * company服务层
 *
 * @author
 */
@Service
public class CompanyService {
    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<Company> findAll() {
        return companyDao.findAll();
    }


    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<Company> findSearch(Map whereMap, int page, int size) {
        Specification<Company> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return companyDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<Company> findSearch(Map whereMap) {
        Specification<Company> specification = createSpecification(whereMap);
        return companyDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public Company findById(String id) {
        return companyDao.findById(id).orElse(null);
    }

    /**
     * 增加
     *
     * @param company
     */
    public void add(Company company) {

        LocalDateTime now = LocalDateTime.now();
        company.setCreatedAt(now);
        company.setUpdatedAt(now);
        company.setIsChain("0");
        company.setRealNameStatus("0");
        companyDao.save(company);
    }

    /**
     * 修改
     *
     * @param company
     */
    public void update(Company company) {
        companyDao.save(company);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        companyDao.deleteById(id);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Company> createSpecification(Map searchMap) {
        return new Specification<Company>() {
            @Override
            public Predicate toPredicate(Root<Company> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // id
                String id = "id";
                if (searchMap.get(id) != null && !"".equals(searchMap.get(id))) {
                    predicateList.add(cb.like(root.get(id).as(String.class), "%" + (String) searchMap.get(id) + "%"));
                }
                // 公司名称
                String companyName = "companyName";
                if (searchMap.get(companyName) != null && !"".equals(searchMap.get(companyName))) {
                    predicateList.add(cb.like(root.get(companyName).as(String.class), "%" + (String) searchMap.get(companyName) + "%"));
                }
                // 代理商id
                String agentId = "agentId";
                if (searchMap.get(agentId) != null && !"".equals(searchMap.get(agentId))) {
                    predicateList.add(cb.like(root.get(agentId).as(String.class), "%" + (String) searchMap.get(agentId) + "%"));
                }
                // 电话
                String phone = "phone";
                if (searchMap.get(phone) != null && !"".equals(searchMap.get(phone))) {
                    predicateList.add(cb.like(root.get(phone).as(String.class), "%" + (String) searchMap.get(phone) + "%"));
                }
                // 法人真实姓名
                String realName = "realName";
                if (searchMap.get(realName) != null && !"".equals(searchMap.get(realName))) {
                    predicateList.add(cb.like(root.get(realName).as(String.class), "%" + (String) searchMap.get(realName) + "%"));
                }
                // 实名制状态 0-未实名 1-已实名 2-实名失败
                String realNameStatus = "realNameStatus";
                if (searchMap.get(realNameStatus) != null && !"".equals(searchMap.get(realNameStatus))) {
                    predicateList.add(cb.like(root.get(realNameStatus).as(String.class), "%" + (String) searchMap.get(realNameStatus) + "%"));
                }
                // 法人身份证号码
                String idCard = "idCard";
                if (searchMap.get(idCard) != null && !"".equals(searchMap.get(idCard))) {
                    predicateList.add(cb.like(root.get(idCard).as(String.class), "%" + (String) searchMap.get(idCard) + "%"));
                }
                // 营业执照号码
                String businessLicense = "businessLicense";
                if (searchMap.get(businessLicense) != null && !"".equals(searchMap.get(businessLicense))) {
                    predicateList.add(cb.like(root.get(businessLicense).as(String.class), "%" + (String) searchMap.get(businessLicense) + "%"));
                }
                // 省份
                String province = "province";
                if (searchMap.get(province) != null && !"".equals(searchMap.get(province))) {
                    predicateList.add(cb.like(root.get(province).as(String.class), "%" + (String) searchMap.get(province) + "%"));
                }
                // 省份id
                String provinceId = "provinceId";
                if (searchMap.get(provinceId) != null && !"".equals(searchMap.get(provinceId))) {
                    predicateList.add(cb.like(root.get(provinceId).as(String.class), "%" + (String) searchMap.get(provinceId) + "%"));
                }
                // 城市
                String city = "city";
                if (searchMap.get(city) != null && !"".equals(searchMap.get(city))) {
                    predicateList.add(cb.like(root.get(city).as(String.class), "%" + (String) searchMap.get(city) + "%"));
                }
                // 城市id
                String cityId = "cityId";
                if (searchMap.get(cityId) != null && !"".equals(searchMap.get(cityId))) {
                    predicateList.add(cb.like(root.get(cityId).as(String.class), "%" + (String) searchMap.get(cityId) + "%"));
                }
                // 区县
                String area = "area";
                if (searchMap.get(area) != null && !"".equals(searchMap.get(area))) {
                    predicateList.add(cb.like(root.get(area).as(String.class), "%" + (String) searchMap.get(area) + "%"));
                }
                // 区县id
                String areaId = "areaId";
                if (searchMap.get(areaId) != null && !"".equals(searchMap.get(areaId))) {
                    predicateList.add(cb.like(root.get(areaId).as(String.class), "%" + (String) searchMap.get(areaId) + "%"));
                }
                // 详细地址
                String address = "address";
                if (searchMap.get(address) != null && !"".equals(searchMap.get(address))) {
                    predicateList.add(cb.like(root.get(address).as(String.class), "%" + (String) searchMap.get(address) + "%"));
                }
                // 备注
                String remark = "remark";
                if (searchMap.get(remark) != null && !"".equals(searchMap.get(remark))) {
                    predicateList.add(cb.like(root.get(remark).as(String.class), "%" + (String) searchMap.get(remark) + "%"));
                }
                // 是否连锁店 0-否 1-是
                String isChain = "isChain";
                if (searchMap.get(isChain) != null && !"".equals(searchMap.get(isChain))) {
                    predicateList.add(cb.like(root.get(isChain).as(String.class), "%" + (String) searchMap.get(isChain) + "%"));
                }
                //剔除软删除数据
                String deletedAt = "deletedAt";
                predicateList.add(cb.equal(root.get(deletedAt), cb.nullLiteral(Date.class)));

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }

    public void sendSms(String phone) {
        /**
         * 生成4位数字随机数
         */
        String checkCode = RandomStringUtils.randomNumeric(4);
        /**
         * 向缓存中放一份
         */
        String redisKey = Constant.MERCHANT_LOGIN_CAPTCHA + phone;
        redisTemplate.opsForValue().set(redisKey, checkCode, 10, TimeUnit.MINUTES);
        /**
         * 给用户发一份
         */
        Map<String, String> map = new HashMap<>(2);
        map.put("phone", phone);
        map.put("checkCode", checkCode);
        /**
         * 为方便测试，先不实现短信的发送，直接在后台显示
         */
        rabbitTemplate.convertAndSend("sms", map);
        /**
         * 在控制台显示一份【方便测试】
         */
        System.out.println("the phone is:" + phone + ",the checkCode is:" + checkCode + ",the<" + redisTemplate.opsForValue().get("sendSmsCount_" + phone) + ">time");
    }

    /**
     * 通过agentId查询company列表
     *
     * @param agentId
     * @return
     */
    public List<Company> findAllByAgentId(String agentId) {
        return companyDao.findAllByAgentId(agentId);
    }


}
